package cn.stylefeng.guns.modular.tool.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.stylefeng.guns.modular.order.service.OrderPutService;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.justCgrkApi;
import cn.stylefeng.guns.core.util.justShThApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.entity.BasicPosition;
import cn.stylefeng.guns.modular.basic.entity.BasicTray;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicTrayParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicTrayResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.order.entity.OrderPut;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.order.model.params.OrderPutDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.result.OrderPutDetailedResult;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.modular.tool.entity.ToolOrderPut;
import cn.stylefeng.guns.modular.tool.entity.ToolOrderPutDetailed;
import cn.stylefeng.guns.modular.tool.model.params.ToolOrderPutDetailedParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolOrderPutParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolStorageStockParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolOrderPutDetailedResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolOrderPutResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolStorageStockResult;
import cn.stylefeng.guns.modular.tool.service.ToolOrderPutDetailedService;
import cn.stylefeng.guns.modular.tool.service.ToolOrderPutService;
import cn.stylefeng.guns.modular.tool.service.ToolStorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 云仓入库表控制器
 *
 * @author zhucx
 * @Date 2023-04-03 15:38:25
 */
@Controller
@RequestMapping("/toolOrderPut")
public class ToolOrderPutController extends BaseController {

    private String PREFIX = "/tool/toolOrderPut";

    @Autowired
    private ToolOrderPutService toolOrderPutService;

	@Autowired
	private OrderPutService orderPutService;
    @Autowired
    private ToolOrderPutDetailedService toolOrderPutDetailedService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private DictService dictService;

    @Autowired
    private BasicPositionService basicPositionService;
    
    @Autowired
    private BasicGoodsService basicGoodsService;

    @Autowired
    private ToolStorageStockService toolStorageStockService;
    
    private Lock lock = new ReentrantLock();

    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-04-03
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/toolOrderPut.html";
    }
    
    /**
     * 批量入库 页面
     */
    @RequestMapping("tobtnPut")
    public String tobtnPut(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/btnPut.html";
    }
    
	/**
	 * 撤回
	 * 直接入库
	 */
    @RequestMapping("/revoke")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ResponseData revoke(ToolOrderPutParam toolOrderPutParam) {
		//修改入库订单状态
        toolOrderPutParam.setBillstate("REVOKED");
        toolOrderPutService.update(toolOrderPutParam);
		
        ToolOrderPut toolOrderPut = toolOrderPutService.getById(toolOrderPutParam.getId());
        ToolOrderPutDetailedParam orderPutDetailedParam = new ToolOrderPutDetailedParam();
        orderPutDetailedParam.setPutDetailedNumber(toolOrderPut.getPutNumber());
        List<ToolOrderPutDetailedResult> dlist = toolOrderPutDetailedService.findListBySpec(orderPutDetailedParam);
        for (ToolOrderPutDetailedResult r : dlist) {
        	ToolStorageStockParam storageStockParam = new ToolStorageStockParam();
        	storageStockParam.setGoodsId(r.getDetailedGoodsnum());
        	storageStockParam.setWarehouseId(toolOrderPut.getWarehouseId());
        	List<ToolStorageStockResult> slist = toolStorageStockService.findListBySpec(storageStockParam);
        	if(slist.size()==0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //Manual rollback
        		return ResponseData.error("Inventory has changed!");
        	}
			BasicGoods bG = basicGoodsService.getById(r.getDetailedGoodsnum());//商品
			BigDecimal detailedPutnum = new BigDecimal(r.getDetailedPutnum());//入库数量
			BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
			BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
			BigDecimal u = new BigDecimal(bG.getGoodsCharging());//单价compareTo
			BigDecimal as = new BigDecimal(0);
        	for (ToolStorageStockResult sr : slist) {
    			BigDecimal num = new BigDecimal(sr.getNum());//库存数
        		if(num.compareTo(detailedPutnum) == 1) {
        			num = num.subtract(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN);
        			ToolStorageStockParam storageStockUpdate = new ToolStorageStockParam();
        			storageStockUpdate.setId(sr.getId());
        			storageStockUpdate.setNum(num.toString());
        			storageStockUpdate.setStockWeight(w.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
        			storageStockUpdate.setStockVolume(v.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
        			storageStockUpdate.setUnitprice(u.toString());
        			storageStockUpdate.setStockMoney(u.multiply(num).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
        			toolStorageStockService.update(storageStockUpdate);
        			detailedPutnum = as;
        			break;
        		}
        		if(num.compareTo(detailedPutnum) == 0) {
        			ToolStorageStockParam storageStockUpdate = new ToolStorageStockParam();
        			storageStockUpdate.setId(sr.getId());
        			toolStorageStockService.delete(storageStockUpdate);
        			detailedPutnum = as;
        			break;
        		}
        		if(num.compareTo(detailedPutnum) == -1) {
        			ToolStorageStockParam storageStockUpdate = new ToolStorageStockParam();
        			storageStockUpdate.setId(sr.getId());
        			toolStorageStockService.delete(storageStockUpdate);
        			detailedPutnum = detailedPutnum.subtract(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
        		}
			}
        	if(detailedPutnum.compareTo(as) == 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //Manual rollback
        		return ResponseData.error("Inventory has changed!");
        	}
		}
		return ResponseData.success();
	}

    /**
     * 批量入库
     */
    @RequestMapping("/put")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public ResponseData put(@RequestParam("ids") Long[] ids,ToolStorageStockParam toolStorageStockParam) {
		User user = userService.getcurrentUser();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		BasicPositionParam basicPositionParam = new BasicPositionParam();
		basicPositionParam.setWarehouseId(Integer.parseInt(toolStorageStockParam.getWarehouseId().toString()));
		basicPositionParam.setPositionAreaId(Integer.parseInt(toolStorageStockParam.getAreaId().toString()));
		basicPositionParam.setPositionNumber(toolStorageStockParam.getPositionNumber());
		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(), user.getOperateId());
		if(basicPositionResult == null) {
			return ResponseData.error(toolStorageStockParam.getPositionNumber()+" location does not exist");
		}
		toolStorageStockParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
		lock.lock();//获取锁
		try {
	    	for (Long id :ids) {
	    		//判断明细是否添加了
				ToolOrderPut toolOrderPut = toolOrderPutService.getById(id);
				if ("PENDING_SUBMIT".equals(toolOrderPut.getBillstate())||"REVOKED".equals(toolOrderPut.getBillstate())) {
					QueryWrapper<ToolOrderPutDetailed> queryWrapper = new QueryWrapper<ToolOrderPutDetailed>();
					queryWrapper.eq("put_detailed_number", toolOrderPut.getPutNumber());
					int count = toolOrderPutDetailedService.count(queryWrapper);
		    		if (count>0) {
		    			BasicWarehouse basicWarehouse = basicWarehouseService.getById(toolOrderPut.getWarehouseId());
		    			BasicPosition basicPosition = basicPositionService.getById(toolStorageStockParam.getPositionId());
		    			
		    			ToolOrderPutDetailedParam putDetailedParam = new ToolOrderPutDetailedParam();
		    			putDetailedParam.setPutDetailedNumber(toolOrderPut.getPutNumber());
		    			List<ToolOrderPutDetailedResult> putDlist = toolOrderPutDetailedService.totalListByGgoodsSpec(putDetailedParam);//合计入库商品明细
		    			for (ToolOrderPutDetailedResult PutD : putDlist) {
		    				BasicGoods bG = basicGoodsService.getById(PutD.getDetailedGoodsnum());//商品
		    				BigDecimal detailedPutnum = new BigDecimal(PutD.getDetailedPutnum());//入库数量
		    				BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
		    				BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
		    				BigDecimal u = new BigDecimal(bG.getGoodsCharging());//单价
		    				BigDecimal as = new BigDecimal(0);
		    				
		    				if(detailedPutnum.compareTo(as) == 1) {
		    	    			ToolStorageStockParam xiangtongParam = new ToolStorageStockParam();
		    	    			xiangtongParam.setPositionId(toolStorageStockParam.getPositionId());
		    	    			xiangtongParam.setGoodsId(PutD.getDetailedGoodsnum());
		    	    			ToolStorageStockResult xiangtongr = toolStorageStockService.findBySpec(xiangtongParam);
		    	    			if(xiangtongr != null) {
		    						BigDecimal xtnum = new BigDecimal(xiangtongr.getNum());
		    	        			ToolStorageStockParam supdate = new ToolStorageStockParam();
		    	        			BigDecimal xshu = detailedPutnum.add(xtnum).setScale(3, BigDecimal.ROUND_HALF_DOWN);//相加
		    	        			supdate.setId(xiangtongr.getId());
		    	        			supdate.setNum(xshu.toString());
	    	    					supdate.setStockWeight(w.multiply(xshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//重量
	    	    					supdate.setStockVolume(v.multiply(xshu).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
	    	    					supdate.setStockMoney(u.multiply(xshu).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//库存金额
	    	    					supdate.setUnitprice(bG.getGoodsCharging());//单价
	    	    					toolStorageStockService.update(supdate);//更新相同库存
		    	    			} else {
		    	    				ToolStorageStockParam param = new ToolStorageStockParam();
			    					param.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
			    					param.setOperateName(basicWarehouse.getWarehouseOperateName());
			    					param.setCustomerId(toolOrderPut.getPutCustomerId());
			    					param.setCustomerName(toolOrderPut.getPutCustomerName());
			    					param.setWarehouseId(toolOrderPut.getWarehouseId());
			    					param.setWarehouseName(toolOrderPut.getWarehouseName());
			    					param.setAreaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
			    					param.setAreaNumber(basicPosition.getAreaNumber());
			    					param.setPositionId(Long.parseLong(basicPosition.getId().toString()));
			    					param.setPositionNumber(basicPosition.getPositionNumber());
			    					param.setGoodsId(PutD.getDetailedGoodsnum());
			    					param.setGoodsNumber(PutD.getGoodsNumber());
			    					param.setGoodsName(PutD.getDetailedGoodsname());
			    					param.setStockstate("IN_STOCK");
			    					param.setDeptId(deptId);
			    					param.setDeliverId(deliverId);
			    					param.setCreateTime(new Date());
			    					param.setNum(detailedPutnum.toString());
			    					param.setStockWeight(PutD.getDetailedPutweight());
			    					param.setStockVolume(PutD.getDetailedPutvolume());
			    					param.setUnitprice(PutD.getDetailedUnitprice());
			    					param.setStockMoney(PutD.getDetailedMoney());
			    					param.setGoodsUnit(PutD.getGoodsUnit());
			    					param.setGoodsSpecs(PutD.getGoodsSpecs());
			    					toolStorageStockService.add(param);
		    	    			}
		    				}
		    			}
		    			ToolOrderPutParam toolOrderPutParam = new ToolOrderPutParam();
		    			toolOrderPutParam.setId(toolOrderPut.getId());
		    			toolOrderPutParam.setBillstate("WAREHOUSED");
		    			toolOrderPutService.update(toolOrderPutParam);
					} else {
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
						return ResponseData.error("Please add product details first");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return ResponseData.success();
    }
    
    /**
     * 拉取聚水潭退货入库明细  页面
     */
    @RequestMapping("topulljstreturngoods")
    public String topulljstreturngoods(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/pulljstreturngoods.html";
    }

    /**
     * 拉取聚水潭退货入库明细
     * @throws InterruptedException 
     * @throws ParseException 
     * @throws IOException 
     */
    @RequestMapping("/pulljstreturngoods")
    @ResponseBody
    public ResponseData pulljstreturngoods(ToolOrderPutParam toolOrderPutParam,String modified_begin, String modified_end) throws InterruptedException, ParseException, IOException  {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(modified_begin+" 00:00:00");
		Date date2 = sdf.parse(modified_end+" 23:59:59");
		if(DateUtil.differentDaysByMillisecond(date, date2) > 7) {
    		return ResponseData.error("Time range cannot exceed 7 days");
		}
    	ResponseData resdata = new ResponseData();
    	resdata.setSuccess(true);
    	BasicCustomer basicCustomer = basicCustomerService.getById(toolOrderPutParam.getPutCustomerId());
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
    		return ResponseData.error("Please add Jushuitan appKey in basic customer information");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
    		return ResponseData.error("Please add Jushuitan appSecret in basic customer information");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getAccessToken())) {
    		return ResponseData.error("Please add Jushuitan authorization code in basic customer information");
    	} 

		List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
		Integer page_index = 1;//页数
		boolean has_next = true;//是否有下一页
		while (has_next) {
			//只能分页查询，一页最多50条
			//接口调用频率秒级内不超过5次，分钟内不超过100次
			String data = justShThApi.getSellerItem(basicCustomer.getJustAppkey(),basicCustomer.getJustAppsecret(),basicCustomer.getAccessToken(), modified_begin+" 00:00:00", modified_end+" 23:59:59",page_index.toString());
			JSONObject jsonObject = new JSONObject(data);
			if(jsonObject.get("code").toString().equals("0")) {
				JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
				if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
					if(jsonObject1.get("has_next").toString().equals("false")) {
						has_next = false;
					}
					JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						String warehouse = jsonObject2.get("warehouse").toString();//仓库
						if(!warehouse.equals("Zhengshang Supply Chain Return Warehouse")) {
							continue;
						}
						JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
						for (Object object1 : jsonArray1) {
							OrderPutExcelItem excelItem = new OrderPutExcelItem();
							JSONObject jsonObject3 = new JSONObject(object1.toString());
							
							excelItem.setNotes(modified_begin+" 至 " + modified_end);
							
							String sku_id = jsonObject3.get("sku_id").toString();//商品编码
				        	if(sku_id.equals("1759947952444423")||sku_id.equals("1759325202211891")||sku_id.equals("4967199140507")||sku_id.equals("1759325202211890")
				        			||sku_id.equals("1759947952444420")||sku_id.equals("687374017518")||sku_id.equals("693717971892")
				        			||sku_id.equals("caixiang")
				        			||sku_id.equals("qipaodai-05")
				        			||sku_id.equals("goodcard5")
				        			||sku_id.equals("goodcard2")
				        			||sku_id.equals("TM-R0")||sku_id.equals("TM-NK")
				        			||sku_id.equals("TM-RO")
				        			||sku_id.equals("zhixiang")||sku_id.equals("zhixiang-A1")||sku_id.equals("zhixiang-A3")
				        			||sku_id.equals("会员福利卡")||sku_id.equals("瑜大公子卡片")||sku_id.equals("纸箱包装")) {
				        		continue;
				        	}
							excelItem.setGoodsNumber(sku_id);

							String name = jsonObject3.get("name").toString();//商品名称
							excelItem.setGoodsName(name);
							if(ToolUtil.isEmpty(name)) {
								excelItem.setGoodsName(sku_id);
							}

							String r_qty = jsonObject3.get("r_qty").toString();//实收退货数量
							excelItem.setPutnum(r_qty);
							list.add(excelItem);
						}
					}
				} else {
					has_next = false;
					resdata.setSuccess(false);
					resdata.setMessage("未获取到快递明细");
				}
			} else {
				has_next = false;
				resdata.setSuccess(false);
				resdata.setMessage("拉取失败！"+data);
			}
			page_index++;
			if(has_next) {
				Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
			}
		}
		if(list.size()>0) {
			resdata = toolOrderPutService.savePulljstreturngoods(toolOrderPutParam,list);
		}
		return resdata; 
    }
    
    /**
     * 拉取聚水潭采购入库单  页面
     */
    @RequestMapping("topulljstputorder")
    public String topulljstputorder(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/pulljstputorder.html";
    }

	/**
	 * 拉取聚水潭采购入库单  页面
	 */
	@RequestMapping("topulljstputorderNew")
	public String topulljstputorderNew(Model model) {
		User user = userService.getcurrentUser();
		Long deptId = user.getDeptId();
		Long deliverId = user.getDeliverId();
		//查询可选择仓库
		model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
		//查询可选择客户
		model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
		return PREFIX + "/pulljstputorderNew.html";
	}
    /**
     * 拉取聚水潭采购入库单
     * @throws InterruptedException 
     * @throws ParseException 
     * @throws IOException 
     */
    @RequestMapping("/pulljstputorder")
    @ResponseBody
    public ResponseData pulljstputorder(ToolOrderPutParam toolOrderPutParam,String modified_begin, String modified_end) throws InterruptedException, ParseException, IOException  {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(modified_begin+" 00:00:00");
		Date date2 = sdf.parse(modified_end+" 23:59:59");
		if(DateUtil.differentDaysByMillisecond(date, date2) > 7) {
    		return ResponseData.error("时间不能超过7天");
		}
    	ResponseData resdata = new ResponseData();
    	resdata.setSuccess(true);
    	BasicCustomer basicCustomer = basicCustomerService.getById(toolOrderPutParam.getPutCustomerId());
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
    		return ResponseData.error("请添加基础信息客户聚水潭appKey");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
    		return ResponseData.error("请添加基础信息客户聚水潭appSecret");
    	} 
    	if(ToolUtil.isEmpty(basicCustomer.getAccessToken())) {
    		return ResponseData.error("请添加基础信息客户聚水潭客户授权码");
    	} 

		List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
		Integer page_index = 1;//页数
		boolean has_next = true;//是否有下一页
		while (has_next) {
			//只能分页查询，一页最多50条
			//接口调用频率秒级内不超过5次，分钟内不超过100次
			String data = justCgrkApi.getSellerItem(basicCustomer.getJustAppkey(),basicCustomer.getJustAppsecret(),basicCustomer.getAccessToken(), modified_begin+" 00:00:00", modified_end+" 23:59:59",page_index.toString());
			JSONObject jsonObject = new JSONObject(data);
			if(jsonObject.get("code").toString().equals("0")) {
				JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
				if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
					if(jsonObject1.get("has_next").toString().equals("false")) {
						has_next = false;
					}
					JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						String out_oi_id = jsonObject2.get("out_io_id").toString();//外部单号
						JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
						for (Object object1 : jsonArray1) {
				            OrderPutExcelItem excelItem = new OrderPutExcelItem();
							excelItem.setShipmentnumber(out_oi_id);
							JSONObject jsonObject3 = new JSONObject(object1.toString());
							String sku_id = jsonObject3.get("sku_id").toString();//商品编码
							excelItem.setGoodsNumber(sku_id);

							String name = jsonObject3.get("name").toString();//商品名称
							excelItem.setGoodsName(name);

							String qty = jsonObject3.get("qty").toString();//入库数量
							excelItem.setPutnum(qty);
							list.add(excelItem);
						}
					}
				} else {
					has_next = false;
					resdata.setSuccess(false);
					resdata.setMessage("未获取到快递明细");
				}
			} else {
				has_next = false;
				resdata.setSuccess(false);
				resdata.setMessage("拉取失败！"+data);
			}
			page_index++;
			if(has_next) {
				Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
			}
		}
		if(list.size()>0) {
			resdata = toolOrderPutService.savePulljstputorder(toolOrderPutParam,list);
		}
		return resdata; 
    }



	/**
	 * 拉取聚水潭采购入库单
	 * @throws InterruptedException
	 * @throws ParseException
	 * @throws IOException
	 */
	@RequestMapping("/pulljstputorderNew")
	@ResponseBody
	public ResponseData pulljstputorderNew(OrderPutParam orderPutParam,String modified_begin, String modified_end) throws InterruptedException, ParseException, IOException  {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(modified_begin);
		Date date2 = sdf.parse(modified_end);
		if(DateUtil.differentDaysByMillisecond(date, date2) > 7) {
			return ResponseData.error("时间不能超过7天");
		}
		User user = userService.getcurrentUser();
		ResponseData resdata = new ResponseData();
		resdata.setSuccess(true);
		BasicCustomer basicCustomer = basicCustomerService.getById(orderPutParam.getPutCustomerId());
		if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
			return ResponseData.error("请添加基础信息客户聚水潭appKey");
		}
		if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
			return ResponseData.error("请添加基础信息客户聚水潭appSecret");
		}
		if(ToolUtil.isEmpty(basicCustomer.getAccessToken())) {
			return ResponseData.error("请添加基础信息客户聚水潭客户授权码");
		}


		Integer page_index = 1;//页数
		boolean has_next = true;//是否有下一页
		while (has_next) {

			//只能分页查询，一页最多50条
			//接口调用频率秒级内不超过5次，分钟内不超过100次
			String data = justCgrkApi.getSellerItemNew(basicCustomer.getJustAppkey(),
					basicCustomer.getJustAppsecret(),
					basicCustomer.getAccessToken(),
					modified_begin,
					modified_end,
					page_index.toString());
			JSONObject jsonObject = new JSONObject(data);
			if(jsonObject.get("code").toString().equals("0")) {
				JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
				if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
					if(jsonObject1.get("has_next").toString().equals("false")) {
						has_next = false;
					}
					JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
					List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
					List<OrderPutExcelItem> list1 = new ArrayList<OrderPutExcelItem>();
					for (Object object : jsonArray) {

						JSONObject jsonObject2 = new JSONObject(object.toString());
						if(!((14648074 ==jsonObject2.getInt("wms_co_id") &&
								orderPutParam.getPutCustomerId()==132 &&
								orderPutParam.getWarehouseId()==96) ||
								(15260317 ==jsonObject2.getInt("wms_co_id") &&
								orderPutParam.getPutCustomerId()==147 &&
								orderPutParam.getWarehouseId()==122))){
							continue;
						}
//						if(!(15260317 ==jsonObject2.getInt("wms_co_id") &&
//								orderPutParam.getPutCustomerId().equals(132) &&
//								orderPutParam.getWarehouseId().equals(96))){
//							continue;
//						}
						if("大坝".equals(jsonObject2.getString("supplier_name"))){
							continue;
						}
						String type = jsonObject2.getString("type");
						System.err.println(type);
						String io_id = jsonObject2.get("io_id").toString().replace("null", "");//外部单号);//外部单号
						JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
						JSONArray batchsJsonArray = new JSONArray(jsonObject2.get("batchs").toString());
						jsonArray1.forEach(item ->{
							cn.hutool.json.JSONObject jsonObjectitem = new cn.hutool.json.JSONObject(item.toString());
							OrderPutExcelItem excelItem = new OrderPutExcelItem();
							excelItem.setShipmentnumber(io_id);
							String sku_id = jsonObjectitem.get("sku_id").toString();//商品编码
							excelItem.setGoodsNumber(sku_id);

							String name = jsonObjectitem.get("name").toString();//商品名称
							excelItem.setGoodsName(name);
							batchsJsonArray.forEach(batch -> {
								cn.hutool.json.JSONObject bajsonObject = new cn.hutool.json.JSONObject(batch.toString());
								if (bajsonObject.getStr("sku_id").equals(jsonObjectitem.getStr("sku_id"))) {
									excelItem.setGoodsbatchs(bajsonObject.getStr("batch_no"));
									excelItem.setBatchnumber(bajsonObject.getStr("product_date"));
								}
							});
							String qty = jsonObjectitem.get("qty").toString();//入库数量
							excelItem.setPutnum(qty);
							if("采购进仓".equals(type)){
								list.add(excelItem);
							}

						});
						if(list.size()>0) {
							orderPutService.savePulljstputorder(user,orderPutParam,list);
						}
					}

				} else {
					has_next = false;
					resdata.setSuccess(false);
					resdata.setMessage("未获取到快递明细");
				}
			} else {
				has_next = false;
				resdata.setSuccess(false);
				resdata.setMessage("拉取失败！"+data);
			}
			page_index++;
			if(has_next) {
				Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
			}


		}

		return resdata;
	}


	/**
	 * 武汉聚水潭出库订单
	 * @param orderPutParam
	 * @param modified_begin
	 * @param modified_end
	 * @return
	 * @throws InterruptedException
	 * @throws ParseException
	 * @throws IOException
	 */
	@RequestMapping("/pullWhJstPutOrder")
	@ResponseBody
	public ResponseData pullWhJstPutOrder(OrderPutParam orderPutParam,String modified_begin, String modified_end) throws InterruptedException, ParseException, IOException  {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(modified_begin);
		Date date2 = sdf.parse(modified_end);
		if(DateUtil.differentDaysByMillisecond(date, date2) > 7) {
			return ResponseData.error("时间不能超过7天");
		}
		User user = userService.getcurrentUser();
		ResponseData resdata = new ResponseData();
		resdata.setSuccess(true);
		BasicCustomer basicCustomer = basicCustomerService.getById(orderPutParam.getPutCustomerId());
		if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
			return ResponseData.error("请添加基础信息客户聚水潭appKey");
		}
		if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
			return ResponseData.error("请添加基础信息客户聚水潭appSecret");
		}
		if(ToolUtil.isEmpty(basicCustomer.getAccessToken())) {
			return ResponseData.error("请添加基础信息客户聚水潭客户授权码");
		}


		Integer page_index = 1;//页数
		boolean has_next = true;//是否有下一页
		while (has_next) {

			//只能分页查询，一页最多50条
			//接口调用频率秒级内不超过5次，分钟内不超过100次
			String data = justCgrkApi.getSellerItemNew(basicCustomer.getJustAppkey(),
					basicCustomer.getJustAppsecret(),
					basicCustomer.getAccessToken(),
					modified_begin,
					modified_end,
					page_index.toString());
			JSONObject jsonObject = new JSONObject(data);
			if(jsonObject.get("code").toString().equals("0")) {
				JSONObject jsonObject1 = new JSONObject(jsonObject.get("data").toString());
				if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
					if(jsonObject1.get("has_next").toString().equals("false")) {
						has_next = false;
					}
					JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
					List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
					List<OrderPutExcelItem> list1 = new ArrayList<OrderPutExcelItem>();
					for (Object object : jsonArray) {

						JSONObject jsonObject2 = new JSONObject(object.toString());
						if(!((14648074 ==jsonObject2.getInt("wms_co_id") &&
								orderPutParam.getPutCustomerId()==132 &&
								orderPutParam.getWarehouseId()==96) ||
								(15260317 ==jsonObject2.getInt("wms_co_id") &&
										orderPutParam.getPutCustomerId()==147 &&
										orderPutParam.getWarehouseId()==122))){
							continue;
						}
//						if(!(15260317 ==jsonObject2.getInt("wms_co_id") &&
//								orderPutParam.getPutCustomerId().equals(132) &&
//								orderPutParam.getWarehouseId().equals(96))){
//							continue;
//						}
						if("大坝".equals(jsonObject2.getString("supplier_name"))){
							continue;
						}
						String type = jsonObject2.getString("type");
						System.err.println(type);
						String io_id = jsonObject2.get("io_id").toString().replace("null", "");//外部单号);//外部单号
						JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
						JSONArray batchsJsonArray = new JSONArray(jsonObject2.get("batchs").toString());
						jsonArray1.forEach(item ->{
							cn.hutool.json.JSONObject jsonObjectitem = new cn.hutool.json.JSONObject(item.toString());
							OrderPutExcelItem excelItem = new OrderPutExcelItem();
							excelItem.setShipmentnumber(io_id);
							String sku_id = jsonObjectitem.get("sku_id").toString();//商品编码
							excelItem.setGoodsNumber(sku_id);

							String name = jsonObjectitem.get("name").toString();//商品名称
							excelItem.setGoodsName(name);
							batchsJsonArray.forEach(batch -> {
								cn.hutool.json.JSONObject bajsonObject = new cn.hutool.json.JSONObject(batch.toString());
								if (bajsonObject.getStr("sku_id").equals(jsonObjectitem.getStr("sku_id"))) {
									excelItem.setGoodsbatchs(bajsonObject.getStr("batch_no"));
									excelItem.setBatchnumber(bajsonObject.getStr("product_date"));
								}
							});
							String qty = jsonObjectitem.get("qty").toString();//入库数量
							excelItem.setPutnum(qty);
							if("采购进仓".equals(type)){
								list.add(excelItem);
							}

						});
						if(list.size()>0) {
							orderPutService.savePulljstputorder(user,orderPutParam,list);
						}
					}

				} else {
					has_next = false;
					resdata.setSuccess(false);
					resdata.setMessage("未获取到快递明细");
				}
			} else {
				has_next = false;
				resdata.setSuccess(false);
				resdata.setMessage("拉取失败！"+data);
			}
			page_index++;
			if(has_next) {
				Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
			}


		}

		return resdata;
	}
    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	List<DictResult> dictLists =  dictService.findByDicttypeCode2("SETTLEMENT_METHOD");//结算方式 字典
    	model.addAttribute("dictLists", dictLists);
    	
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	
    	//查询可选择仓库
    	model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import.html";
    }
    
    /**
     * 下载入库订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/toolOrderPut.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("云仓入库模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传excel   
     */
	@RequestMapping(value = "/importExceNewmethodl" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  ToolOrderPutParam toolOrderPutParam)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = toolOrderPutService.getExceldata(file,toolOrderPutParam,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-04-03
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	List<DictResult> dictList =  dictService.findByDicttypeCodeAndDictCode3("BUSINESS_CATEGORY","RKZL");//入库种类 字典
    	model.addAttribute("dictList", dictList);
    	List<DictResult> dictListm =  dictService.findByDicttypeCodeAndDictCode3("BUSINESS_CATEGORY","MODES");//出入库方式 字典
    	model.addAttribute("dictListm", dictListm);
    	List<DictResult> dictLists =  dictService.findByDicttypeCode2("SETTLEMENT_METHOD");//结算方式 字典
    	model.addAttribute("dictLists", dictLists);
    	
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	
    	//查询可选择仓库
    	model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/toolOrderPut_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-04-03
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	List<DictResult> dictList =  dictService.findByDicttypeCodeAndDictCode3("BUSINESS_CATEGORY","RKZL");//入库种类 字典
    	model.addAttribute("dictList", dictList);
    	List<DictResult> dictListm =  dictService.findByDicttypeCodeAndDictCode3("BUSINESS_CATEGORY","MODES");//出入库方式 字典
    	model.addAttribute("dictListm", dictListm);
    	List<DictResult> dictLists =  dictService.findByDicttypeCode2("SETTLEMENT_METHOD");//结算方式 字典
    	model.addAttribute("dictLists", dictLists);
    	
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	
    	//查询可选择仓库
    	model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/toolOrderPut_edit.html";
    }
    
    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(ToolOrderPutParam toolOrderPutParam) {
    	User user = userService.getcurrentUser();
    	//校验客户单号 是否存在
    	if (this.toolOrderPutService.checkCustomerOrder(toolOrderPutParam.getPutCustomerNumber())) {
    		return ResponseData.error("客户单号已存在");
		} 
    	
    	Long DeliverId = user.getDeliverId();
    	if (DeliverId!=null) {
    		toolOrderPutParam.setDeliverId(DeliverId);//set 交付id
		}
    	Long deptId = user.getDeptId();
    	if (deptId!=null) {
    		toolOrderPutParam.setDeptId(deptId);//set 部门id
		}
		String trayCode = getOperateIdOrderPrefix(user);
    	Object WarehouseId = toolOrderPutParam.getWarehouseId();
    	if (WarehouseId!=null) {
			BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
			toolOrderPutParam.setWarehouseName(bawBasicWarehouse.getWarehouseName());//set 仓库名称
		}
    	Object CustomerId = toolOrderPutParam.getPutCustomerId();
    	if (CustomerId!=null) {
    		BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
    		toolOrderPutParam.setPutCustomerName(basicCustomer.getCustomerName());//set 客户名称
    		toolOrderPutParam.setSettlementunit(basicCustomer.getCustomerSettlement());//结算单位
		}
    	toolOrderPutParam.setBillstate("PENDING_SUBMIT");//set 单据状态
    	toolOrderPutParam.setCreateName(user.getName());//set 制单用户名称
    	
    	ToolOrderPut toolOrderPut = this.toolOrderPutService.findByThelastone();
    	if (toolOrderPut!=null) {
    		toolOrderPutParam.setPutNumber(trayCode+"-"+"YCRK-"+DateUtil.getDateBch()+"-"+(toolOrderPut.getId()+1));
		} else {
			toolOrderPutParam.setPutNumber(trayCode+"-"+"YCRK-"+DateUtil.getDateBch()+"-"+"1");
		}
        this.toolOrderPutService.add(toolOrderPutParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(ToolOrderPutParam toolOrderPutParam) {
    	//校验客户单号 是否存在
    	ToolOrderPut toolOrderPut = this.toolOrderPutService.getById(toolOrderPutParam.getId());
    	if (!toolOrderPut.getPutCustomerNumber().equals(toolOrderPutParam.getPutCustomerNumber())) {
        	if (this.toolOrderPutService.checkCustomerOrder(toolOrderPutParam.getPutCustomerNumber())) {
        		return ResponseData.error("客户单号已存在");
    		}
		}
    	
    	Object WarehouseId = toolOrderPutParam.getWarehouseId();
    	if (WarehouseId!=null) {
			BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
			toolOrderPutParam.setWarehouseName(bawBasicWarehouse.getWarehouseName());//set 仓库名称
		}
    	Object CustomerId = toolOrderPutParam.getPutCustomerId();
    	if (CustomerId!=null) {
    		BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
    		toolOrderPutParam.setPutCustomerName(basicCustomer.getCustomerName());//set 客户名称
		}

        this.toolOrderPutService.update(toolOrderPutParam);
        return ResponseData.success();
    }

	@Autowired
    private DeptService deptService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

    /**
     * 批量作废
     */
    @RequestMapping("/tovoid")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public ResponseData tovoid(@RequestParam("ids") Long[] ids) {
    	for (Long id :ids) {
	        ToolOrderPut detail = this.toolOrderPutService.getById(id);
	        if (detail.getBillstate().equals("PENDING_SUBMIT")||detail.getBillstate().equals("REVOKED")) {
	        	ToolOrderPutParam param = new ToolOrderPutParam();
	        	param.setId(Integer.parseInt(id.toString()));
	        	param.setBillstate("CANCELLED");
	        	toolOrderPutService.update(param);
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("只可作废待提交单据");
			}
		}
        return ResponseData.success();
    }

    /**
     * 发起
     */
    @RequestMapping("/launch")
    @ResponseBody
    public ResponseData launch(ToolOrderPutParam param) {
    	ToolOrderPut toolOrderPut = toolOrderPutService.getById(param.getId());
		param.setPutCustomerNumber(toolOrderPut.getPutCustomerNumber());
		ToolOrderPutResult toolOrderPutResult = toolOrderPutService.findBySpec(param,null);
    	if (toolOrderPutResult!=null) {
    		return ResponseData.error("客户单号已存在");
		}
    	param.setBillstate("PENDING_SUBMIT");
    	toolOrderPutService.update(param);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-04-03
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(ToolOrderPutParam toolOrderPutParam) {
        ToolOrderPut detail = this.toolOrderPutService.getById(toolOrderPutParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-04-03
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(ToolOrderPutParam toolOrderPutParam,String condition,String startTime,String endTime ) {
    	User user = userService.getcurrentUser();
    	toolOrderPutParam.setDeliverId(user.getDeliverId());
    	toolOrderPutParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		toolOrderPutParam.setCreateName("'"+startTime+"' and '"+endTime+"'");
		}
        return this.toolOrderPutService.findPageBySpec(toolOrderPutParam,condition,user.getOperateId());
    }

}


